//
//  FKTabBar.m
//  FKTabBarController
//
//  Created by 云眼科技 on 16/7/30.
//  Copyright © 2016年 CloudEyes. All rights reserved.
//

#import "FKTabBar.h"
#import "UIView+FKAdd.h"

#pragma mark- ==============================> FKTabBarItem begin <============================

@interface FKTabBarItem ()
@property (nonatomic, strong) CAShapeLayer *indicatorLayer;
@property (nonatomic, strong) FKBageValueLabel *bageValueLabel;
@end

@implementation FKTabBarItem

- (instancetype)init{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

-(void)commonInit{
    self.opaque = YES;
    self.titleLabel.opaque = YES;
    self.titleLabel.font = [UIFont systemFontOfSize:self.frame.size.height/2];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    _itemType = FKTabBarItemTypePoint;
    _bageValue = 0; 
}

-(CGRect)titleRectForContentRect:(CGRect)contentRect{
    return contentRect;
}

-(void)setItemType:(FKTabBarItemType)itemType{
    _itemType = itemType;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat width = self.bounds.size.width /6;
    CGRect pathRect = CGRectMake(1.5, 1.5, width - 3, width - 3);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:width/2];
    _indicatorLayer.frame = CGRectMake(self.bounds.size.width-width, width/2, width, width);
    _indicatorLayer.path = path.CGPath;
}

-(void)setBageValue:(NSInteger)bageValue{
    _bageValue = bageValue;
    NSString *string = [NSString stringWithFormat:@"%ld", bageValue];
    CGFloat stringWidth = [string sizeWithAttributes:@{NSFontAttributeName:self.bageValueLabel.font}].width + 6;
    CGFloat width = stringWidth > self.bounds.size.height/2 ? stringWidth : self.bounds.size.height/2;
    self.bageValueLabel.frame = CGRectMake(self.bounds.size.width - self.bounds.size.height/2, 0, width, self.bounds.size.height/2);
    self.bageValueLabel.bageValue = bageValue;
}


-(void)addIndicator{
    switch (self.itemType) {
        case FKTabBarItemTypePoint:
            [self.layer addSublayer:self.indicatorLayer];
            break;
        case FKTabBarItemTypeBageValue:
            [self addSubview:self.bageValueLabel];
            break;
    }
}

-(void)removeIndicator{
    switch (self.itemType) {
        case FKTabBarItemTypePoint:
            [self.indicatorLayer removeFromSuperlayer];
            break;
        case FKTabBarItemTypeBageValue:
            [self.bageValueLabel removeFromSuperview];
            break;
    }
}

-(CAShapeLayer *)indicatorLayer{
    if (!_indicatorLayer) {    
        CGFloat width = self.bounds.size.width /6;
        _indicatorLayer = [CAShapeLayer layer];
        _indicatorLayer.opaque = YES;
        _indicatorLayer.frame = CGRectMake(self.bounds.size.width-width, 0, width, width);
        _indicatorLayer.strokeColor = [UIColor redColor].CGColor;
        _indicatorLayer.fillColor = [UIColor whiteColor].CGColor;
        _indicatorLayer.lineWidth = 2.f;
        CGRect pathRect = CGRectMake(1.5, 1.5, width - 3, width - 3);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:width/2];
        _indicatorLayer.path = path.CGPath;
    }
    return _indicatorLayer;
}


-(FKBageValueLabel *)bageValueLabel{
    if (!_bageValueLabel) {
        CGFloat lableWidth = self.bounds.size.height/2;
        _bageValueLabel = [[FKBageValueLabel alloc] initWithFrame:CGRectMake(self.bounds.size.width - lableWidth, 0, lableWidth, lableWidth)];
    }
    return _bageValueLabel;
}

@end

#pragma mark- ==============================> FKTabBarItem end <============================



@implementation FKBageValueLabel

- (instancetype)init{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit]; 
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

-(void)commonInit{  
    self.opaque = YES;
    self.font = [UIFont systemFontOfSize:self.frame.size.height/2];
    self.contentMode = UIViewContentModeScaleAspectFill;
    self.textAlignment = NSTextAlignmentCenter;
    self.textColor = [UIColor whiteColor];
    self.backgroundColor = [UIColor redColor];
    self.layer.cornerRadius = self.bounds.size.height/2;
    self.layer.masksToBounds = YES;
}

-(void)setBageValue:(NSInteger)bageValue{
    _bageValue = bageValue;
    if (bageValue <= 0) {
        [self removeFromSuperview];
    }else if (bageValue > 0 && bageValue <= 99){
        self.text = [NSString stringWithFormat:@"%ld", bageValue];
    }else{
        self.text = @"99+";
    }
}




@end

@interface FKBackgroundView ()
@property (nonatomic, strong) CAShapeLayer *roundRectLayer;
@end

@implementation FKBackgroundView

- (instancetype)init{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

-(void)commonInit{
    self.opaque = YES;
    _type = FKBackgroundViewTypeRoundRectStroke;
    _strokeColor = [UIColor redColor];

    switch (_type) {
        case FKBackgroundViewTypeRoundRectFill:
            _fillColor = [UIColor redColor];
            break;
        case FKBackgroundViewTypeRoundRectStroke:
            _fillColor = [UIColor whiteColor];
            break;
    }
    
    [self.layer addSublayer:self.roundRectLayer];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.bounds.size.height/2];
    self.roundRectLayer.frame = self.bounds;
    self.roundRectLayer.path = path.CGPath;
}

-(void)setFillColor:(UIColor *)fillColor{
    _fillColor = fillColor;
}

-(void)setStrokeColor:(UIColor *)strokeColor{
    _strokeColor = strokeColor;
}

-(void)setType:(FKBackgroundViewType)type{
    _type = type;
    switch (_type) {
        case FKBackgroundViewTypeRoundRectFill:
            self.roundRectLayer.fillColor = self.strokeColor.CGColor;
            break;
        case FKBackgroundViewTypeRoundRectStroke:
            self.roundRectLayer.fillColor = self.fillColor.CGColor;
            break;
    }
}


-(CAShapeLayer *)roundRectLayer{
    if (!_roundRectLayer) {
        _roundRectLayer = [CAShapeLayer layer];   
        _roundRectLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
        _roundRectLayer.fillColor = self.fillColor.CGColor;
        _roundRectLayer.strokeColor = self.strokeColor.CGColor;
        _roundRectLayer.lineWidth = 1.f;
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) cornerRadius:self.bounds.size.height/2];
        _roundRectLayer.path = path.CGPath;
    }
    return _roundRectLayer;
}


@end


#define ScaleNum 1.2
#define BtnBaseTag 10086
#define MaxItemNum 6

@interface FKTabBar (){
    FKBackgroundView *_backgroundView;
    UIView *_lineView;
    NSMutableArray <FKTabBarItem *> *_itemArray;
}
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation FKTabBar

-(instancetype)initWithFrame:(CGRect)frame titleArray:(nullable NSArray<NSString *> *)titleArray{
    self = [super initWithFrame:frame];
    if (self) {
//        [self commonInit];
        
        _selectStyle = FKTabBarSelectedStyleColorChange;
        _barStyle = FKTabBarStyleNone;
        _needAnimation = YES;
        _barTintColor = nil;
        _lineColor = nil;
        _titleArray = [[NSArray alloc] init];
        _indicatorView = nil;
        _itemSpacing = 5.f;
        
        _itemArray = [[NSMutableArray alloc] init];
        
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        [self addSubview:_scrollView];
        
        [titleArray enumerateObjectsUsingBlock:^(NSString * _Nonnull title, NSUInteger index, BOOL * _Nonnull stop) {
            FKTabBarItem *tempItem = [[FKTabBarItem alloc] init];
            tempItem.itemType = FKTabBarItemTypePoint;
            [tempItem setTitle:title forState:UIControlStateNormal];
            [tempItem addTarget:self action:@selector(itemPressed:) forControlEvents:UIControlEventTouchUpInside];
            tempItem.tag = index + BtnBaseTag;
            if (index == 0) {
                tempItem.selected = YES;  
                self.selectedItem = tempItem;
                [self excuteDelegateWithIndex:index andItem:tempItem];
//                [self.selectedItem makeTransformWithScale:ScaleNum];
                [tempItem addIndicator];
            }
            [_scrollView addSubview:tempItem];
            [_itemArray addObject:tempItem];
        }];
        _itemWidth = frame.size.width / 5;
        _titleArray = titleArray;
    }
    return self;
}

-(void)excuteDelegateWithIndex:(NSInteger)index andItem:(FKTabBarItem *)item{
    if (self.delegate &&[self.delegate respondsToSelector:@selector(tabBar:didSelectItem:)]) {
        [self.delegate tabBar:self didSelectItem:item];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBar:didSelectItemAtIndex:)]) {
        [self.delegate tabBar:self didSelectItemAtIndex:index];
    }
}


-(void)layoutSubviews{
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
    [self setBaseViewContentSize];
    [_itemArray enumerateObjectsUsingBlock:^(FKTabBarItem * _Nonnull btn, NSUInteger index, BOOL * _Nonnull stop) {
        btn.frame = [self getBtnFrameWithIndex:index];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];  
        btn.titleLabel.font = [UIFont systemFontOfSize:btn.view_height*6/7/2];
    }];
}

-(void)setBaseViewContentSize{
    self.scrollView.contentSize = CGSizeMake([self getBtnWidth] * self.titleArray.count, self.frame.size.height);
}

-(CGRect)getBtnFrameWithIndex:(NSInteger)index{
    CGFloat btn_w = [self getBtnWidth];
    CGFloat btn_h = self.frame.size.height;
    CGFloat btn_x = self.bounds.origin.x + btn_w * index;
    return CGRectMake(btn_x, 0, btn_w, btn_h);
}

-(CGFloat)getBtnWidth{
    CGFloat width;
    if (self.titleArray.count >= MaxItemNum) {
        width = self.frame.size.width / (MaxItemNum + 1);
    }else{
        width = self.frame.size.width / self.titleArray.count;
    }
    return width;
}

-(void)itemPressed:(FKTabBarItem *)item{
    if (!(item.selected == NO && item != self.selectedItem)) return; 
    
    if (self.titleArray.count >= MaxItemNum) {
        CGPoint offset = CGPointMake([self getOffsetWithView:item], 0);
        [self.scrollView setContentOffset:offset animated:YES];
    }     
    
    [self resetSelectedBtnScale];
    self.selectedItem.selected = NO;
    item.selected = YES;
//    [UIView animateWithDuration:0.3 animations:^{
//        item.transform = CGAffineTransformScale(CGAffineTransformIdentity, ScaleNum, ScaleNum);
//    }];
    self.selectedItem = item;
    NSInteger tag = item.tag - BtnBaseTag;
    if (self.delegate &&[self.delegate respondsToSelector:@selector(tabBar:didSelectItem:)]) {
        [self.delegate tabBar:self didSelectItem:item];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBar:didSelectItemAtIndex:)]) {
        [self.delegate tabBar:self didSelectItemAtIndex:tag];
    }
}

-(void)resetSelectedBtnScale{
    [UIView animateWithDuration:0.3 animations:^{
        self.selectedItem.transform = CGAffineTransformIdentity;
    }];
}

-(CGFloat)getOffsetWithView:(UIView *)view{
    CGFloat offsetX = view.center.x - self.frame.size.width * 0.5;
    CGFloat maxOffsetX = self.scrollView.contentSize.width - self.frame.size.width;
    if (offsetX < 0) {
        offsetX = 0;
    }
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    return offsetX;
}


-(void)moveToItemAtIndex:(NSInteger)index animation:(BOOL)animation{
    
}

-(void)addNewMessageToItem:(FKTabBarItem *)item atIndex:(NSInteger)index{
    
}



@end
